//
//  SetViewController.m
//  Light
//
//  Created by 骁唐 on 15/8/27.
//  Copyright (c) 2015年 骁唐. All rights reserved.
//

#import "SetViewController.h"
#import "ConnectViewController.h"
#import "AppDelegate.h"
#import "LoginViewController.h"
#import "UserConfig.h"
#import "ConnectOnViewController.h"
#import "BluetoothController.h"

@interface SetViewController ()<ConnectOnViewControllerDelegate,UIGestureRecognizerDelegate,UIAlertViewDelegate>
//背景图片
@property (weak, nonatomic) IBOutlet UIImageView *backGround;
//弹窗蒙版
@property (weak, nonatomic) IBOutlet UIView *maskView;
//弹窗
@property (weak, nonatomic) IBOutlet UIView *alterView;

@property (strong,nonatomic) BluetoothController *defaultBTServer;

@end

@implementation SetViewController
{
    UIAlertView *cancelAlert;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    self.navigationController.interactivePopGestureRecognizer.delegate = self;
    UserConfig *config = [UserConfig sharingUserConfig];
    NSString *cool = [config getConnectCool];
    if ([cool intValue] == 1)
    {
        self.removeLabel.text = @"解除绑定";
        [self checkBLEInfo];//只有当绑定设备的状态下，才检查蓝牙固件信息是否已经读取
    }
    else
    {
        self.removeLabel.text = @"绑定设备";
    }
    //
    //[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(endReportInfo:) name:@"cancelConnect" object:nil];
    //
    //    if (delegate.Bluetooth) {
    //        self.removeLabel.text = @"解除绑定";
    //    }else
    //    {
    //        self.removeLabel.text = @"绑定设备";
    //    }
    // Do any additional setup after loading the view.
}

/*
 检查 蓝牙版本是否为空 如果为空，需要再次读取，如果不为空，则不处理。
 */
- (void)checkBLEInfo
{    
    //需要判断是否处于绑定连接状态   读取蓝牙适配器版本信息指令
    AppDelegate * delegate = [[UIApplication sharedApplication] delegate];
    UserConfig * config = [UserConfig sharingUserConfig];
    if (delegate.Bluetooth)
    {//如果蓝牙 连接
        if ([TJJDefines isNull:[config getBLEHardware]])
        {//如果蓝牙固件版本没有读取到
            [TJJ_SD_BLE_INSTRUCTIONS readBLEHardInfo];//读取蓝牙适配器版本信息指令
        }
        else
        {//固件序列号版本已经读取到了，不用处理
        }
    }
    else
    {//如果蓝牙 未处于连接状态
    }
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
    return  YES;
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldBeRequiredToFailByGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
    return [gestureRecognizer isKindOfClass:UIScreenEdgePanGestureRecognizer.class];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    //禁用滑动手势
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    }
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */
#pragma mark -
#pragma mark 解除绑定按钮or绑定设备
- (IBAction)releaseClick {
    AppDelegate *delegate = [[UIApplication sharedApplication]delegate];
    if ([self.removeLabel.text isEqualToString:@"绑定设备"]) {//如果是绑定设备点击。
        
        NSLog(@"断开后%@",delegate.peripheral);
        //切换storyboard
        UIStoryboard *connect = [UIStoryboard storyboardWithName:@"Login" bundle:nil];
        ConnectViewController *connectVc = [connect instantiateViewControllerWithIdentifier:@"connectViewId"];//根据id设置
        connectVc.mark = YES;//标记从设置进入的连接设备操作
        [self.navigationController pushViewController:connectVc animated:YES];
        //        [self presentViewController:connectVc animated:YES completion:nil];
        
    }
    else
    {//如果是解除绑定点击
        
        UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"您确定要解除眼罩绑定？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        alertView.tag = 291;
        [alertView show];
        
    }
}

- (void)judgeCancelConnect  //暂时没用到
{
    AppDelegate *delegate = [[UIApplication sharedApplication] delegate];
    if (delegate.myRemoveConnect) {
        [cancelAlert dismissWithClickedButtonIndex:0 animated:YES];
        TJJALERT_VIEW(@"解除绑定失败！");
    }else
    {
    }
}

#pragma mark -
#pragma mark 解除绑定操作
- (void)UnBind{
//    AppDelegate *delegate = [[UIApplication sharedApplication]delegate];
//    delegate.myRemoveConnect = YES;//标记是用户自己点击的解除绑定
//    if (delegate.peripheral != nil)
//    {
//        UserConfig *config = [UserConfig sharingUserConfig];
//        [config setConnectCool:@"0"];
//        NSData *data  = [TJJ_SD_BLE_INSTRUCTIONS writeString:SD_SEND_REMOVE_BINDING];//下位机断开连接
//        [delegate.peripheral writeValue:data
//                      forCharacteristic:delegate.writeCharacteristic
//                                   type:CBCharacteristicWriteWithResponse];
//        [delegate.mgr disConnect];//解除绑定操作
//    }
//    //本地绑定设备信息修改。
//    UserConfig *config = [UserConfig sharingUserConfig];
//    [config setConnectCool:@"0"];//设定绑定状态为0.解绑状态
//    [config setBlueToothKey:nil];//清除key
//    [config setBluetoothAddress:nil];//清除UUID
//    [config setSerialNumber:@"0"];
//    [config setHardware:@"0"];
    //打开解除绑定弹窗
    [UIView animateWithDuration:0.5 animations:^{
        self.alterView.hidden = NO;
        self.maskView.hidden = NO;
        self.alterView.alpha = 1.f;
        self.maskView.alpha = 0.4f;
    }];
}

#pragma mark -
#pragma mark 解除绑定弹窗确定btn
- (IBAction)releaseAlterClick {
    //    UIStoryboard *connect = [UIStoryboard storyboardWithName:@"Login" bundle:nil];
    //    [self.navigationController pushViewController:[connect instantiateViewControllerWithIdentifier:@"connectViewId"] animated:YES];) {
    self.removeLabel.text = @"绑定设备";
    self.alterView.alpha = 0.f;
    self.maskView.alpha = 0.f;
    self.alterView.hidden = YES;
    self.maskView.hidden = YES;
    AppDelegate *delegate = [[UIApplication sharedApplication]delegate];
    UserConfig *config = [UserConfig sharingUserConfig];
    [config setBluetoothAddress:@""];
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithCapacity:0];
    [dict setObject:@"NO" forKey:@"disConnect"];
    //发送电量改变的通知
    [[NSNotificationCenter defaultCenter] postNotificationName:@"power" object:nil userInfo:dict];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"userHead" object:nil userInfo:dict];
    delegate.Bluetooth = NO;
    delegate.myRemoveConnect = YES;
    NSLog(@"123");
}

#pragma mark -
#pragma mark 帮助手册点击
- (IBAction)helpClick {
    
    [self performSegueWithIdentifier:@"setToHelp" sender:nil];
}

#pragma mark -
#pragma mark 关于我们点击
- (IBAction)aboutUserClick {
    [self performSegueWithIdentifier:@"setToAboutUser" sender:nil];
}

#pragma mark -
#pragma mark 返回上一界面
- (IBAction)backClick {
    
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark -
#pragma mark 设置背景颜色
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    //强制竖屏
    [[UIDevice currentDevice] setValue:[NSNumber numberWithInteger:
                                        UIInterfaceOrientationPortrait]  forKey:@"orientation"];
    self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    long long int currentTimeInt = [TJJDefines getTimeIntSince1970Current];
    if (currentTimeInt>=16200&& currentTimeInt <=34200) {
        self.backGround.image = [UIImage imageNamed:@"backgroundOne"];
    }else if (currentTimeInt>34200 && currentTimeInt<=55800)
    {
        self.backGround.image = [UIImage imageNamed:@"backgroundTwo"];
    }else if (currentTimeInt>55800 && currentTimeInt<=70200)
    {
        self.backGround.image = [UIImage imageNamed:@"backgroundThree"];
    }else if(currentTimeInt >70200 || currentTimeInt<16200)
    {
        self.backGround.image = [UIImage imageNamed:@"background_night"];
    }
    
    UserConfig *config = [UserConfig sharingUserConfig];
    if ([[config getConnectCool]  intValue] == 1) {
        self.removeLabel.text = @"解除绑定";
    }else
    {
        self.removeLabel.text = @"绑定设备";
    }
    
    
}
#pragma mark -
#pragma mark 退出登录
- (IBAction)quitBtnClick {
    UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"您确定要退出当前用户？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    alertView.tag = 292;
    [alertView show];
}

#pragma mark -
#pragma mark 清除用户登录信息
- (void)clearUserInfo
{
    UserConfig *config = [UserConfig sharingUserConfig];
    [config setHaveLogin:@"lalala"];
    [config setToken:@"123"];
    [config setUserHeadData:nil];
    
    UIStoryboard *LoginSt = [UIStoryboard storyboardWithName:@"Login" bundle:nil];
    LoginViewController *loginVc = [LoginSt instantiateViewControllerWithIdentifier:@"loginViewId"];
    loginVc.quit = YES;
    [self.navigationController pushViewController:loginVc animated:YES];
}

#pragma mark -
#pragma mark 实现ConnectOnViewController控制器的协议方法
- (void)sendValue:(NSString *)value
{
    self.removeLabel.text = value;
}

#pragma mark -
#pragma mark delegete 弹出框
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    NSInteger tagNumber = alertView.tag;
    switch (tagNumber) {
        case 291:
        {//解除设备绑定
            switch (buttonIndex) {
                case 0:
                {//取消
                    NSLog(@"取消");
                }
                    break;
                case 1:
                {//确定
                    [TJJ_SD_BLE_INSTRUCTIONS unBind:@"key"];//解除绑定操作
                    [self UnBind];//解除绑定操作
                }
                    break;
                default:
                    break;
            }

        }
            break;
        case 292:
        {//退出登录
            switch (buttonIndex) {
                case 0:
                {//取消
                    NSLog(@"取消");
                }
                    break;
                case 1:
                {//确定
                    
                    [TJJ_SD_BLE_INSTRUCTIONS unBind:@"key"];//解除绑定操作
                    [self clearUserInfo];//清楚用户登录信息

                    //                    [delegate.mgr disConnect];//断开设备连接
//                    AppDelegate *delegate = [[UIApplication sharedApplication]delegate];
//                    delegate.myRemoveConnect = YES;//标记是用户自己点击的解除绑定
//                    UserConfig *config = [UserConfig sharingUserConfig];
//                    [config setConnectCool:@"0"];
//                    NSData *data  = [TJJ_SD_BLE_INSTRUCTIONS writeString:SD_SEND_REMOVE_BINDING];//下位机断开连接
//                    [delegate.peripheral writeValue:data
//                                  forCharacteristic:delegate.writeCharacteristic
//                                               type:CBCharacteristicWriteWithResponse];
//                    
//                    [delegate.mgr disConnect];//解除绑定操作
                }
                    break;
                default:
                    break;
            }
            
        }
            break;
            
        default:
            break;
    }
   
}

@end
